package com.lilosoft.core.xss;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import com.lilosoft.core.utils.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;


public class XssFilter implements Filter {

	private final Log logger = LogFactory.getLog(this.getClass());

    FilterConfig filterConfig = null;

    private List<String> urlExclusion = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String servletPath = httpServletRequest.getServletPath();
        String path = httpServletRequest.getRequestURL().toString();
    	logger.info("===XssFilter===");
        logger.info("request url : " + path);
        logger.info("ServletPath : " + servletPath);

        // 前端路由请求 或者 后台无需权限验证的请求
        if (!servletPath.contains(".do") || StringUtils.urlIsMatches(urlExclusion, servletPath)) {
        	chain.doFilter(request, response);
        } else {
        	chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
        }
    }

    public List<String> getUrlExclusion() {
        return urlExclusion;
    }

    public void setUrlExclusion(List<String> urlExclusion) {
        this.urlExclusion = urlExclusion;
    }


}
